<? if ($c = stack('name')) {

	$s = component_settings($c);
//dbdebug();

//debug($tid = gccHuuid(param('id')));
	if (($tid = gccHuuid(param('id'))) && 
		($ticket = datafetch('db_item', 'cs_ticket', "id=$tid AND kind=".TK_NEW_USER))) {

//debug($ticket);

		$person = json_decode($ticket['data'], true);

		if (($person['email'] = h($person['email'])) && datafetch('db_item', 'cs_person', "email='$person[email]'")) {
//debug('this email is already registered');
			header("Location: "._transformURL($CURRENT->url, array('remove_params' => 'all', 'add_level' => 'wrong')));
			exit;
		}

//debug($person, 'person', 1);
		$val = gccPersonStore($person);
//debug($val, 'person', 1);

		if ($val['stored']) {
			
			$uuid = gccGetUUID();
			$person_id = trim($val['data']);

			datafetch('db_insert', 'cs_person', $vuser = array(
				'id' => $uuid, 
				'email' => $person['email'],
				'pass' => pwd($person['pass'], $person['email']),
				'person_id' => $person_id,
				'auth_id' => AI_REGULAR_USER,
			));


			$_SESSION['reg'] = false;

			datafetch('db_delete', 'cs_ticket', "id=$tid AND kind=".TK_NEW_USER);
			
			

			if ($user = datafetch('db_item', tb('auth'), "id=$vuser[auth_id]")) {
	
				$user['time'] = date("H:i");
				
				$user['vuser'] = array_merge($vuser, gccLoadPerson($vuser['person_id']));	// load person data
				
				$user['settings'] = json_decode($user['settings'], true);
				if (!is_array($user['settings'])) $user['settings'] = array();
				
				create_session($user);
			}
					
			header("Location: "._transformURL($CURRENT->url, array('remove_params' => 'all', 'add_level' => 'complete')));
			exit;
		
		} else {
			
//debug('failed');
			$_SESSION['reg'] = $person;

			header("Location: "._transformURL($CURRENT->url, array('remove_params' => 'all', 'add_level' => 'failed')));
			exit;

		}

	} else {

//debug('wrong code');
		header("Location: "._transformURL($CURRENT->url, array('remove_params' => 'all', 'add_level' => 'wrong')));
		exit;
	}

unstack();
}